﻿using System;
using System.IO;
using System.Windows.Forms;
using System.ServiceModel;
using ajayumi.develop.win32.Transport.Utils.WinForm;
using ajayumi.develop.win32.Transport.WCF.Services;

namespace ajayumi.develop.win32.Transport.Client.WinForm.Controls
{
    /// <summary>
    /// UcFailure.cs 故障信息用户控件
    /// Author   : 黄乙冬
    /// Date     : 2011-11-09
    /// </summary>
    public partial class UcFault : UserControl
    {
        #region Variables

        private readonly TransFileCollection m_UploadFileCollection = new TransFileCollection();
        private readonly FileListener m_FileListener = null;

        #endregion

        public Action<string> Display { get; set; }

        public UcFault()
        {
            InitializeComponent();

            ControlHelper.DoubleBuffered(this.dgvUploadFiles, true);
            this.dgvUploadFiles.AutoGenerateColumns = false;
            this.dgvUploadFiles.DataSource = this.m_UploadFileCollection;

            this.m_FileListener = new FileListener(
                () => { return AppConfig.ListenFile; },
                (text) => this.RaiseDisplay(text));
            this.m_FileListener.UploadFile = (file, path) =>
            {
                file.MoveTo(path);
                this.dgvUploadFiles.Invoke(new Action<string, string[]>(this.InvokeUploadFile),
                    new object[] { string.Empty, new string[] { path } });
            };

            //this.Play();
            //this.Stop();
        }

        /// <summary>
        /// 打开监听
        /// </summary>
        /// <param name="value"></param>
        private void Play()
        {
            this.tsbtnPlay.Enabled = false;
            this.tsbtnStop.Enabled = true;

            this.m_FileListener.Start();
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        private void Stop()
        {
            this.tsbtnPlay.Enabled = true;
            this.tsbtnStop.Enabled = false;

            this.m_FileListener.Stop();
        }

        private void InvokeUploadFile(string rootPath, string[] files)
        {

            foreach (string item in files)
            {
                //MCUServiceClient client = new MCUServiceClient();

                //string relativePath = Path.GetFileName(item);
                //if (string.IsNullOrEmpty(rootPath))
                //{
                //    rootPath = Path.GetDirectoryName(item);
                //}
                //else
                //{
                //    relativePath = item.Replace(rootPath, string.Empty).TrimStart('\\');
                //}

                //UploadFile uploadFile = new UploadFaultLogFile(rootPath, relativePath,
                //    (file) => { return client.InitUploadFile(file); },
                //    (file) => { return client.UploadFile(file); });
                //uploadFile.GetBufferSize = () => { return AppConfig.BufferSize; };
                //uploadFile.TransReady += (sender, e) =>
                //{
                //    this.m_UploadFileCollection.TransFileReady(e.RelativePath,
                //        FileHelper.FormatFileSize(e.FileLength),
                //        e.ProgressPercentage);
                //};
                //uploadFile.TransProgressChanged += (sender, e) =>
                //{
                //    this.m_UploadFileCollection.TransFileProgressChanged(e.RelativePath, e.ProgressPercentage);
                //    this.RaiseDisplay(string.Format("{0} {1} 上传故障日志文件进度：{2}%.\r\n", DateTime.Now, e.RelativePath, e.ProgressPercentage));
                //};
                //uploadFile.TransCompleted += (sender, e) =>
                //{
                //    this.m_UploadFileCollection.TransFileCompleted(e);

                //    if (e.Error != null)
                //    { this.RaiseDisplay(string.Format("{0} {1} 上传故障日志文件时发生错误。错误信息：\r\n{2}\r\n", DateTime.Now, e.RelativePath, e.Error.Message)); }
                //    else
                //    {
                //        this.RaiseDisplay(string.Format("{0} {1} 上传故障日志文件完毕.\r\n", DateTime.Now, e.RelativePath));
                //    }

                //    try
                //    {
                //        client.Close();
                //    }
                //    catch (FaultException ex)
                //    {
                //        client.Abort();
                //        this.RaiseDisplay(string.Format("{0} {1} 上传故障日志文件时发生错误。错误信息：\r\n{2}\r\n", DateTime.Now, e.RelativePath, ex.Message));
                //    }
                //    catch (TimeoutException ex)
                //    {
                //        client.Abort();
                //        this.RaiseDisplay(string.Format("{0} {1} 上传故障日志文件时发生错误。错误信息：\r\n{2}\r\n", DateTime.Now, e.RelativePath, ex.Message));
                //    }
                //    catch (Exception ex)
                //    {
                //        client.Abort();
                //        this.RaiseDisplay(string.Format("{0} {1} 上传故障日志文件时发生错误。错误信息：\r\n{2}\r\n", DateTime.Now, e.RelativePath, ex.Message));
                //    }
                //};

                //FileInfo fileInfo = new FileInfo(item);
                //TransFileItem transFileItem = new TransFileItem()
                //{
                //    Name = fileInfo.Name,
                //    RelativePath = relativePath,
                //    FileSize = FileHelper.FormatFileSize(fileInfo.Length),
                //    ProgressPercentage = string.Empty
                //};
                //this.m_UploadFileCollection.Add(transFileItem);

                //uploadFile.RunWorkAsync();
            }
        }

        private void RaiseDisplay(string text)
        {
            if (this.Display != null)
            { this.Display(text); }
        }

        private void tsbtnPlay_Click(object sender, EventArgs e)
        {
            this.Play();
        }

        private void tsbtnStop_Click(object sender, EventArgs e)
        {
            this.Stop();
        }

        private void tsbtnClearUploadCmp_Click(object sender, EventArgs e)
        {
            this.m_UploadFileCollection.ClearCompleted();
        }
    }
}
